package crp.extensions.scy.sso.models;

import com.qwlabs.exceptions.ExternalException;
import crp.extensions.scy.sso.SCYResponseUtil;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;

import java.util.Optional;

@Builder
@AllArgsConstructor
@Getter
public class SCYUserInfo {
    private static final String TAG_USERNAME = "cas:username";
    private static final String TAG_ID_CARD = "cas:edupersoncard";
    private static final String TAG_PHONE = "cas:phone";
    private static final String TAG_EMAIL = "cas:email";
    private static final String TAG_REAL_NAME = "cas:realname";
    private static final String TAG_GENDER = "cas:sex";
    private static final String TAG_USER_TYPE = "cas:usertype";

    private final String username;
    private final String idCard;
    private final String phone;
    private final String email;
    private final String realName;
    private final SCYUserGender gender;
    private final SCYUserType userType;

    public static SCYUserInfo of(String response) {
        SCYUserInfo result = SCYUserInfo.builder()
                .username(SCYResponseUtil.getAttribute(response, TAG_USERNAME))
                .idCard(SCYResponseUtil.getAttribute(response, TAG_ID_CARD))
                .phone(SCYResponseUtil.getAttribute(response, TAG_PHONE))
                .email(SCYResponseUtil.getAttribute(response, TAG_EMAIL))
                .realName(SCYResponseUtil.getAttribute(response, TAG_REAL_NAME))
                .gender(new SCYUserGender(SCYResponseUtil.getAttribute(response, TAG_GENDER)))
                .userType(new SCYUserType(SCYResponseUtil.getAttribute(response, TAG_USER_TYPE)))
                .build();
        if (!result.valid()) {
            throw new ExternalException("invalid response:" + response);
        }
        return result;
    }

    private boolean valid() {
        return username != null;
    }

    public Optional<String> getFacultyNo() {
        return Optional.ofNullable(userType)
                .filter(SCYUserType::isFaculty)
                .map(ut -> username);
    }

    public Optional<String> getStudentNo() {
        return Optional.ofNullable(userType)
                .filter(SCYUserType::isStudent)
                .map(ut -> username);
    }
}
